import { createSlice } from '@reduxjs/toolkit'
import { productsApiSlice } from '../../../api/productsApiSlice'

export const DEFAULT_PAGE = 1
export const DEFAULT_ITEMS_PER_PAGE = 20

type TNavigationState = {
	catalogPagination: {
		selectedPage: number
		maxPage: number
	}
}

const initialState: TNavigationState = {
	catalogPagination: {
		selectedPage: DEFAULT_PAGE,
		maxPage: DEFAULT_PAGE,
	},
}

const sliceName = 'pagination'

export const paginationSlice = createSlice({
	name: sliceName,
	initialState,
	reducers: {
		setPage: (state, action) => {
			state.catalogPagination.selectedPage = action.payload
		},
	},
	extraReducers: (builder) => {
		builder.addMatcher(
			productsApiSlice.endpoints.getProducts.matchFulfilled,
			(state, { payload }) => {
				state.catalogPagination.maxPage = Math.ceil(
					payload.total / DEFAULT_ITEMS_PER_PAGE
				)
			}
		)
	},
})
